import base64
import time

import serial
import os
import serial.tools.list_ports
# import receive_part
port_lists=list(serial.tools.list_ports.comports())
# print(port_lists)
def open_serial(port_name):
    try:
        mid_serial=serial.Serial(port_name,baudrate=115200,timeout=0.5)
        print(f'{port_name} opend')
        return mid_serial
    except Exception as e:
        print(e.args[1][e.args[1].find('[Errno')::])#e.args[1].rfind(':')
# if len(port_lists)==2:
#
#     Send_serial=open_serial(port_lists[0].device)
#     # Send_serial = open_serial(/dev/ttyUSB0)
#     # Receive_serial = open_serial(port_lists[1].device)
#
# else:
#     print('串口数量不匹配 请手动选择')

Send_serial=open_serial('/dev/ttyUSB0')

def generate_random_data(size_in_bytes,intervals):


    b1=str(time.time()).encode('utf-8')+'ylj'.encode()+str(intervals)[-1].encode()

    b2=os.urandom(size_in_bytes - len(b1))

    return b1+b2


def send(data,intervals):
    Send_serial.write(data)
    time.sleep(intervals)

# def recv(size,random_data,intervals):
#     recv_data=Receive_serial.read(size)
#
#     marker = recv_data.find(b'ylj')
#     if marker == -1:
#         raise ValueError("Data format is incorrect")
#         # 提取时间戳和随机数据
#     timestamp = recv_data[:marker]
#     stop_time=time.time() - float(timestamp.decode())
#     print()
#     if recv_data==random_data:
#         print(f'read full data  size:{size} ')
#         print(f'lose time: {round(stop_time-intervals,8)} \nintervals : {intervals}')
#     else:
#
#         if len(recv_data)==size:
#             print('receive data but data error')
#         else:
#             print(f'loss some data {size-len(recv_data)}')
#     random_data = recv_data[marker + 3:]  # 3 是 'ylj' 的长度
#     return
#     # return timestamp.decode('utf-8'), random_data


    
# size = 21  # 生成size>21 节的随机数据
# random_data = generate_random_data(size)
# intervals=0.3#s
#
# send(random_data,intervals)
# recv(size,random_data,intervals)
# print(f'send data: {random_data}')
# print()
def test_1():
    size_list=[i for i in range(25,100,10)]
    print(size_list)
    intervals_list=[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7]
    for s in size_list:
        for t in intervals_list:
            random_data = generate_random_data(s,t)
            print()
            print(f'size {s}; data {random_data}; intervals {t}')
            send(random_data,t)
            # receive_part.recv(s)
            print()
            break
test_1()


